//
//  KRRecipeIntroCell.m
//  cookBook
//
//  Created by kuroken on 16/1/24.
//  Copyright © 2016年 kuroken. All rights reserved.
//

#import "KRRecipeIntroCell.h"
#import <PureLayout.h>
#import <UIImageView+WebCache.h>
#import <UIButton+WebCache.h>
#import "KRRecipeLikeBtn.h"
#import "KRConst.h"
#import "KRRecipeInfo.h"

#define KRLog(...)

// cell重用标识
static NSString * const KRRecipeIntroID = @"recipeIntro";

const CGFloat KRRecipePadding = 20;
const CGFloat KRRecipeFontSize = 17;

@interface KRRecipeIntroCell ()
/** 封面 imageView */
@property (nonatomic, weak) UIImageView *coverImageView;
/** 喜欢/收藏 button */
@property (nonatomic, weak) KRRecipeLikeBtn *recipeLikeBtn;
/** 喜欢/收藏数 label */
@property (nonatomic, weak) UILabel *recipeLikeCountLabel;

/** 标题 label */
@property (nonatomic, weak) UILabel *recipeTitleLabel;
/** 头像 button */
@property (nonatomic, weak) UIButton *avatarBtn;
/** 用户名 label */
@property (nonatomic, weak) UILabel *userNameLabel;
/** VIP标识 imageView */
@property (nonatomic, weak) UIImageView *vipImageView;
/** 发布时间 label*/
@property (nonatomic, weak) UILabel *createTimeLabel;
/** 食谱简介 label */
@property (nonatomic, weak) UILabel *recipeIntroLabel;
/** 展开按钮 button */
@property (nonatomic, weak) UIButton *unfoldBtn;

/** 食谱简介高度约束 */
@property (nonatomic, strong) NSLayoutConstraint *recipeIntroLabelHeightConstraint;
/** 食谱简介底部约束 */
@property (nonatomic, strong) NSLayoutConstraint *recipeIntroLabelBottomConstraint;

/** 展开按钮约束 */
@property (nonatomic, strong) NSMutableArray<NSLayoutConstraint *> *unfoldBtnConstraints;

@end

@implementation KRRecipeIntroCell

+ (instancetype)cellWithTableView:(UITableView *)tableView
{
    KRRecipeIntroCell *cell = [tableView dequeueReusableCellWithIdentifier:KRRecipeIntroID];
    if (!cell) {
        cell = [[self alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:KRRecipeIntroID];
    }
    return cell;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        if (!iOS8) {  //iOS7
            self.contentView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
        }
        
        // 设置分隔线长度占满屏幕宽度！？
//        self.separatorInset = UIEdgeInsetsMake(0, MAXFLOAT, 0, 0);
        // 设置分隔线距离右边无限大
//        self.separatorInset = UIEdgeInsetsMake(0, 0, 0, MAXFLOAT);
        
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        
        [self setupSubview];
        [self addConstraint];
    }
    return self;
}

- (void)setRecipeInfo:(KRRecipeInfo *)recipeInfo
{
    _recipeInfo = recipeInfo;
    
    [self.coverImageView sd_setImageWithURL:[NSURL URLWithString:recipeInfo.cover] placeholderImage:[UIImage imageNamed:@"default_r640-414"]];
    [self.recipeLikeBtn setSelected:recipeInfo.isLike];
    [self.recipeLikeCountLabel setText:[recipeInfo.favCount integerValue] > 999 ? @"999+" : recipeInfo.favCount];

    [self.recipeTitleLabel setText:recipeInfo.title];
    [self.avatarBtn sd_setImageWithURL:[NSURL URLWithString:recipeInfo.avatar] forState:UIControlStateNormal];
    [self.userNameLabel setText:recipeInfo.userName];
    [self.createTimeLabel setText:[NSString stringWithFormat:@"原创于%@", recipeInfo.reviewTime]];
    [self.recipeIntroLabel setText:recipeInfo.intro];

    
    if (self.unfoldBtn.isHidden) return;

    CGFloat contentTextWeight = KRScreenWidth - KRRecipePadding * 2;
    CGFloat contentTextHeight = [recipeInfo.intro sizeWithFont:[UIFont systemFontOfSize:KRRecipeFontSize] maxW:contentTextWeight].height; // 内容文字的实际行高
    /* 此时self.recipeIntroLabel还没有尺寸，sizeThatFits计算出来的数值不对 */
    //    CGFloat height = [self.recipeIntroLabel sizeThatFits:CGSizeMake(self.recipeIntroLabel.frame.size.width, MAXFLOAT)].height;
    
    // 内容文字的实际行数
    NSInteger contentLineCount = contentTextHeight / self.recipeIntroLabel.font.lineHeight;
    KRLog(@"%td行", count);
    self.unfoldBtn.hidden = contentLineCount <= 6;
    if (contentLineCount <= 6) {
        self.unfoldBtn.hidden = YES;
        [self.unfoldBtnConstraints autoRemoveConstraints];
        [self.recipeIntroLabelBottomConstraint autoInstall];
    }

}

- (void)setupSubview
{
    /** 封面 imageView */
    UIImageView *coverImageView = [[UIImageView alloc] init];
    coverImageView.userInteractionEnabled = YES;
    coverImageView.contentMode = UIViewContentModeScaleAspectFill;
    coverImageView.clipsToBounds = YES;
    [self.contentView addSubview:coverImageView];
    self.coverImageView = coverImageView;
    
    /** 喜欢/收藏 button */
    KRRecipeLikeBtn *recipeLikeBtn = [[KRRecipeLikeBtn alloc] init];
    [recipeLikeBtn addTarget:self action:@selector(likeBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.coverImageView addSubview:recipeLikeBtn];
    self.recipeLikeBtn = recipeLikeBtn;
    
    /** 喜欢/收藏数 label */
    UILabel *recipeLikeCountLabel = [[UILabel alloc] init];
    [recipeLikeCountLabel setTextColor:[UIColor whiteColor]];
    [recipeLikeCountLabel setFont:[UIFont systemFontOfSize:9]];
    [recipeLikeCountLabel setTextAlignment:NSTextAlignmentCenter];
    [recipeLikeCountLabel setBackgroundColor:KRColor(239, 135, 38)];
    [self.coverImageView addSubview:recipeLikeCountLabel];
    self.recipeLikeCountLabel = recipeLikeCountLabel;

    /** 标题 label */
    UILabel *recipeTitleLabel = [[UILabel alloc] init];
    [recipeTitleLabel setNumberOfLines:0];
    [recipeTitleLabel setFont:[UIFont boldSystemFontOfSize:25]];
    [recipeTitleLabel setTextColor:[UIColor blackColor]];
    [self.contentView addSubview:recipeTitleLabel];
    self.recipeTitleLabel = recipeTitleLabel;
    
    /** 头像 button */
    UIButton *avatarBtn = [[UIButton alloc] init];
    [self.contentView addSubview:avatarBtn];
    self.avatarBtn = avatarBtn;
    
    /** 用户名 label */
    UILabel *userNameLabel = [[UILabel alloc] init];
    [userNameLabel setFont:[UIFont systemFontOfSize:15]];
    [userNameLabel setTextColor:[UIColor blackColor]];
    [self.contentView addSubview:userNameLabel];
    self.userNameLabel = userNameLabel;
    
    /** VIP标识 imageView */
    UIImageView *vipImageView = [[UIImageView alloc] init];
    [vipImageView setImage:[UIImage imageNamed:@"ico_vip"]];
    vipImageView.size = vipImageView.image.size;
    [self.contentView addSubview:vipImageView];
    self.vipImageView = vipImageView;
    
    /** 发布时间 label*/
    UILabel *createTimeLabel = [[UILabel alloc] init];
    [createTimeLabel setFont:[UIFont systemFontOfSize:14]];
    [createTimeLabel setTextColor:[UIColor lightGrayColor]];
    [self.contentView addSubview:createTimeLabel];
    self.createTimeLabel = createTimeLabel;
    
    /** 食谱简介 label */
    UILabel *recipeIntroLabel = [[UILabel alloc] init];
    [recipeIntroLabel setFont:[UIFont systemFontOfSize:KRRecipeFontSize]];
    [recipeIntroLabel setNumberOfLines:6];
    [self.contentView addSubview:recipeIntroLabel];
    self.recipeIntroLabel = recipeIntroLabel;

    /** 展开按钮 button */
    UIButton *unfoldBtn = [[UIButton alloc] init];
    [unfoldBtn setTitle:@"全文" forState:UIControlStateNormal];
    [unfoldBtn setTitle:@"收起" forState:UIControlStateSelected];
    [unfoldBtn setTitleColor:KRColor(111, 143, 18) forState:UIControlStateNormal];
    [unfoldBtn addTarget:self action:@selector(unfoldBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:unfoldBtn];
    self.unfoldBtn = unfoldBtn;
}

/**
 *  点击了展开按钮
 */
- (void)unfoldBtnClick
{
    CGFloat originHeight = [self.recipeIntroLabel sizeThatFits:CGSizeMake(self.recipeIntroLabel.frame.size.width, MAXFLOAT)].height;

    self.unfoldBtn.selected = !self.unfoldBtn.isSelected;
    [self.recipeIntroLabel setNumberOfLines:self.unfoldBtn.isSelected ? 0 : 6];
    
    CGFloat currentHeight = [self.recipeIntroLabel sizeThatFits:CGSizeMake(self.recipeIntroLabel.frame.size.width, MAXFLOAT)].height;
    
    if (self.recipeIntroLabelHeightConstraint) {
        // 移除之前的约束
        [self.recipeIntroLabelHeightConstraint autoRemove];
    }

    [NSLayoutConstraint autoSetPriority:UILayoutPriorityDefaultLow forConstraints:^{
        self.recipeIntroLabelHeightConstraint = [self.recipeIntroLabel autoSetDimension:ALDimensionHeight toSize:currentHeight];
    }];

    CGFloat height = currentHeight - originHeight;
    
    // 调整cell的高度
    if ([self.delegate respondsToSelector:@selector(recipeIntroCellDidClickUnfoldBtn:addHeight:)]) {
        [self.delegate recipeIntroCellDidClickUnfoldBtn:self.unfoldBtn addHeight:height];
    }
}

/**
 *  点击了收藏按钮
 */
- (void)likeBtnClick
{
    self.recipeInfo.like = !self.recipeInfo.isLike;
    self.recipeLikeBtn.selected = !self.recipeLikeBtn.isSelected;
}

- (void)addConstraint
{
    /** 封面 imageView */
    [self.coverImageView autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:0];
    [self.coverImageView autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:0];
    [self.coverImageView autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:0];
    [self.coverImageView autoSetDimension:ALDimensionHeight toSize:250];

    /** 喜欢/收藏 button */
    [self.recipeLikeBtn autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:30];
    [self.recipeLikeBtn autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:20];
    [self.recipeLikeBtn autoSetDimensionsToSize:CGSizeMake(45, 45)];
    self.recipeLikeBtn.layer.cornerRadius = 45 * 0.5;
    self.recipeLikeBtn.clipsToBounds = YES;
    
    /** 喜欢/收藏数 label */
    [self.recipeLikeCountLabel autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:self.recipeLikeBtn withOffset:-18];
    [self.recipeLikeCountLabel autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.recipeLikeBtn withOffset:-18];
    [self.recipeLikeCountLabel autoSetDimensionsToSize:CGSizeMake(27, 27)];
    [self.recipeLikeCountLabel.layer setCornerRadius:27 * 0.5];
    [self.recipeLikeCountLabel setClipsToBounds:YES];

    /** 标题 label */
    [self.recipeTitleLabel autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.coverImageView withOffset:KRRecipePadding];
    [self.recipeTitleLabel autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:KRRecipePadding];
    [self.recipeTitleLabel autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:KRRecipePadding];
    
    /** 头像 button */
    [self.avatarBtn autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.recipeTitleLabel withOffset:10];
    [self.avatarBtn autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:self.recipeTitleLabel];
    [self.avatarBtn autoSetDimensionsToSize:CGSizeMake(40, 40)];
    [[self.avatarBtn layer] setCornerRadius:40 * 0.5];
    [self.avatarBtn setClipsToBounds:YES];
    
    /** 用户名 label */
    [self.userNameLabel autoPinEdge:ALEdgeTop toEdge:ALEdgeTop ofView:self.avatarBtn];
    [self.userNameLabel autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:self.avatarBtn withOffset:10];
    
    /** VIP标识 imageView */
    [self.vipImageView autoPinEdge:ALEdgeTop toEdge:ALEdgeTop ofView:self.avatarBtn];
    [self.vipImageView autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:self.userNameLabel withOffset:5];
    
    /** 发布时间 label*/
    [self.createTimeLabel autoPinEdge:ALEdgeBottom toEdge:ALEdgeBottom ofView:self.avatarBtn];
    [self.createTimeLabel autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:self.userNameLabel];
    
    /** 食谱简介 label */
    [self.recipeIntroLabel autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.avatarBtn withOffset:20];
    [self.recipeIntroLabel autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:self.avatarBtn];
    [self.recipeIntroLabel autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:KRRecipePadding];
    
    [NSLayoutConstraint autoSetPriority:UILayoutPriorityDefaultLow forConstraints:^{
        self.recipeIntroLabelBottomConstraint = [self.recipeIntroLabel autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:KRRecipePadding];
    }];
    
    /** 展开按钮 button */
    NSMutableArray<NSLayoutConstraint *> *unfoldBtnConstraints = [NSMutableArray array];
    [unfoldBtnConstraints addObject:[self.unfoldBtn autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.recipeIntroLabel]];
    [unfoldBtnConstraints addObject:[self.unfoldBtn autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:self.recipeIntroLabel]];
    [unfoldBtnConstraints addObject:[self.unfoldBtn autoSetDimension:ALDimensionHeight toSize:30]];
    [unfoldBtnConstraints addObject:[self.unfoldBtn autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:KRRecipePadding]];
    self.unfoldBtnConstraints = unfoldBtnConstraints;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
